﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.DirectoryServices;
using Auction_Intranet.Models;
using AuctionDataLayer;
using Auction_Intranet.Helpers;
using System.Configuration;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class MakeBidMobileController : ParentController
    {

        DataRepository m_rep = new DataRepository();

        public ActionResult MakeBidMobile()
        {
            BidModel model = new BidModel();

            var StartBidDate = ConfigurationManager.AppSettings["StartingBiddingDate"];
            int startBidYear = Convert.ToInt32(StartBidDate.Split('.')[2]);
            int startBidMonth = Convert.ToInt32(StartBidDate.Split('.')[1]);
            int startBidDay = Convert.ToInt32(StartBidDate.Split('.')[0]);
            DateTime StartingDate = new DateTime(startBidYear, startBidMonth, startBidDay);
            bool ahead = false;
            if (StartingDate.Date > DateTime.Now.AddDays(1).Date)
            {
                ahead = true;
                model.date = StartingDate;
            }
            else 
            {
                model.date = DateTime.Now;            
            }

            var EndBidDate = ConfigurationManager.AppSettings["EndingBiddingDate"];
            int endBidYear = Convert.ToInt32(EndBidDate.Split('.')[2]);
            int endBidMonth = Convert.ToInt32(EndBidDate.Split('.')[1]);
            int endBidDay = Convert.ToInt32(EndBidDate.Split('.')[0]);
            model.dateFinal = new DateTime(endBidYear, endBidMonth, endBidDay);
            if (ahead == false)
            {
                if (model.date.Hour < 20)
                {
                    model.date = model.date.AddDays(1);
                }
                else
                {
                    model.date = model.date.AddDays(2);
                }
            }
            return View(model);
        }

        [HttpPost, ActionName("MakeBidMobile")]
        public ActionResult MakeBidMobile(BidModel model)
        {
            if (ModelState.IsValid)
            {
                bool errorExist = false;
                int bidGroupId = 0;
                var startHour = (model.startTime).Split(':')[0];
                var startMinute = (model.startTime).Split(':')[1];
                var endHour = (model.endTime).Split(':')[0];
                var endMinute = (model.endTime).Split(':')[1];

                var timeStart = new DateTime(1, 1, 1, Convert.ToInt32(startHour), Convert.ToInt32(startMinute), 0);
                var timeEnd = new DateTime(1, 1, 1, Convert.ToInt32(endHour), Convert.ToInt32(endMinute), 0);

                // Validate date
                var tempDate = DateTime.Now;
                if (DateTime.Now.Hour >= 20)
                {
                    tempDate = DateTime.Now.AddDays(1);
                }
                var EndBidDate = ConfigurationManager.AppSettings["EndingBiddingDate"];
                int endBidYear = Convert.ToInt32(EndBidDate.Split('.')[2]);
                int endBidMonth = Convert.ToInt32(EndBidDate.Split('.')[1]);
                int endBidDay = Convert.ToInt32(EndBidDate.Split('.')[0]);
                var endBidDate = new DateTime(endBidYear, endBidMonth, endBidDay);
                var choosenDate = model.date;

                var StartBidDate = ConfigurationManager.AppSettings["StartingBiddingDate"];
                int startBidYear = Convert.ToInt32(StartBidDate.Split('.')[2]);
                int startBidMonth = Convert.ToInt32(StartBidDate.Split('.')[1]);
                int startBidDay = Convert.ToInt32(StartBidDate.Split('.')[0]);
                DateTime StartingDate = new DateTime(startBidYear, startBidMonth, startBidDay);

                if (choosenDate.Date <= tempDate.Date || choosenDate.Date > endBidDate.Date || choosenDate.Date < StartingDate.Date)
                {
                    ModelState.AddModelError("date", "Date not available for bidding");
                    errorExist = true;
                }
                /////////////////////////////////
                if (timeEnd <= timeStart || model.biddingAmount <= 0)
                {
                    if (timeEnd <= timeStart)
                    {
                        ModelState.AddModelError("startTime", "Start time can not be later than end time.");
                    }
                    else if (model.biddingAmount <= 0)
                    {
                        ModelState.AddModelError("biddingAmount", "Bidding amount cannot be 0.");
                    }
                    errorExist = true;
                }
                if (model.bidForId == "1")
                {
                    var tempGroupId = Convert.ToInt32(model.groupId);
                    var tempGroup = m_rep.GetGroupById(tempGroupId);
                    if (tempGroup == null)
                    {
                        ModelState.AddModelError("groups", "You must select a group.");
                        errorExist = true;
                    }
                    else if (model.biddingAmount > tempGroup.Balance)
                    {
                        ModelState.AddModelError("biddingAmount", "Invalid bidding amount");
                        errorExist = true;
                    }
                    bidGroupId = tempGroupId;
                }
                else if (model.bidForId == "0")
                {
                    //create group for my-self only"
                    //|| model.biddingAmount > model.availableCredit
                    var username = (User.Identity.Name).Split('\\')[1];
                    var user = m_rep.GetUserByUsername(username);
                    if (model.biddingAmount > user.Balance)
                    {
                        ModelState.AddModelError("biddingAmount", "Invalid bidding amount");
                        errorExist = true;
                    }
                    bidGroupId = user.MyGroupId;
                }
                if (errorExist)
                {
                    model.date = DateTime.Now;
                    if (DateTime.Now.Hour >= 20)
                    {
                        model.date = DateTime.Now.AddDays(1);
                    }
                    return View(model);
                }
                //No Errors
                //Update data
                //create a group if bid is personal
                var tempRoomId = Convert.ToInt32(model.roomId);
                Bid result1 = new Bid();
                if (tempRoomId != -1)
                {
                    result1.Date = model.date;
                    result1.StartTime = timeStart.AddYears(2000);
                    result1.EndTime = timeEnd.AddYears(2000);
                    result1.GroupId = bidGroupId;
                    result1.BiddingAmount = model.biddingAmount;
                    result1.StateId = 1;
                    result1.RoomId = tempRoomId;
                    result1.AnyRoom = false;
                    result1.AnyRoomId = 0;
                    m_rep.CreateNewBid(result1);
                    m_rep.UpdateBidAnyRoomId(result1.Id);
                }
                else
                {
                    var allRooms = m_rep.GetAllRooms().ToList();
                    result1.Date = model.date;
                    result1.StartTime = timeStart.AddYears(2000);
                    result1.EndTime = timeEnd.AddYears(2000);
                    result1.GroupId = bidGroupId;
                    result1.BiddingAmount = model.biddingAmount;
                    result1.StateId = 1;
                    result1.RoomId = allRooms[0].Id;
                    result1.AnyRoom = true;
                    result1.AnyRoomId = 0;
                    m_rep.CreateNewBid(result1);

                    for (int i = 1; i < allRooms.Count(); i++)
                    {
                        //make bids for all rooms
                        Bid tempResult2 = new Bid();
                        tempResult2.Date = model.date;
                        tempResult2.StartTime = timeStart.AddYears(2000);
                        tempResult2.EndTime = timeEnd.AddYears(2000);
                        tempResult2.GroupId = bidGroupId;
                        tempResult2.BiddingAmount = model.biddingAmount;
                        tempResult2.StateId = 1;
                        tempResult2.RoomId = allRooms[i].Id;
                        tempResult2.AnyRoom = true;
                        tempResult2.AnyRoomId = result1.Id;
                        m_rep.CreateNewBid(tempResult2);
                    }
                    //Update first bid anyroomid
                    m_rep.UpdateBidAnyRoomId(result1.Id);
                }

                var allGroupMembers = m_rep.GetMembersOfGroupById(bidGroupId);
                var calculatedToPay = CalculatEAmountToPay.CalculateAmountSubstract(allGroupMembers, result1.BiddingAmount);

                m_rep.UpdateUserInGroup(calculatedToPay, result1.GroupId, result1.Id);

                //Update single user group if bid if for user
                if (model.bidForId == "0")
                {
                    var username = (User.Identity.Name).Split('\\')[1];
                    User user = m_rep.GetUserByUsername(username);
                    if (user != null)
                    {
                        m_rep.UpdateUserBalance(user.Balance - model.biddingAmount, user.Id);
                        //m_rep.UpdateSingleGroupBalance(model.biddingAmount, user.Id, user.MyGroupId);
                    }
                }

                return RedirectToAction("Index", "Bids");
            }
            model.date = DateTime.Now;
            if (DateTime.Now.Hour >= 20)
            {
                model.date = DateTime.Now.AddDays(1);
            }
            return View(model);
        }
    }
}
